import paramiko
import os
from stat import S_ISDIR


def sftp_get_file(host, port, username, password, remote_path, local_path):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接SSH服务器
        ssh.connect(host, port, username, password)

        # 创建SFTP客户端
        sftp = ssh.open_sftp()

        # 确保本地目录存在
        local_dir = os.path.dirname(local_path)
        if not os.path.exists(local_dir):
            os.makedirs(local_dir)

        # 检查远程路径类型（文件/目录）
        remote_attr = sftp.stat(remote_path)

        if S_ISDIR(remote_attr.st_mode):
            raise Exception("远程路径是目录，不是文件")

        # 传输文件
        sftp.get(remote_path, local_path)
        print(f"文件传输成功: {local_path}")

    except Exception as e:
        print(f"错误发生: {str(e)}")
    finally:
        # 关闭连接
        if 'sftp' in locals():
            sftp.close()
        ssh.close()


if __name__ == "__main__":
    # 银河麒麟服务器配置
    host = "192.168.31.169"  # 替换为实际IP
    port = 22  # 默认SSH端口
    username = "root"  # 替换为实际用户名
    password = "1234qwer!@#$"  # 替换为实际密码

    # 文件路径配置
    remote_file = "/opt/kylin_trace/trace.txt"
    local_relative_path = "kylin_trace/trace.txt"  # 相对路径

    # 转换为绝对路径（相对于当前工作目录）
    local_abs_path = os.path.abspath(local_relative_path)

    # 执行文件传输
    sftp_get_file(host, port, username, password, remote_file, local_abs_path)